﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IOA.MES.DataAccess.Enum;
using IOA.Utils;

namespace IOA.MES.Business
{
    /// <summary>
    /// 等级颜色配置（错误代码：10801）
    /// </summary>
    public class LevelColorMgr
    {
        private MESContext mesDb = new MESContext("MES");

        #region 等级
        /// <summary>
        /// 编辑
        /// </summary>
        public VRankSet EditRank(VRankSet model)
        {
            if (model.PkId <= 0)
            {
                model.CreateTime = DateTime.Now;
                model.ModifyBy = 0;
                var entity = Mapper.Map<RankSet>(model);
                mesDb.RankSets.Add(entity);
                mesDb.SaveChanges();

                model = Mapper.Map<VRankSet>(entity);
            }
            else
            {
                var entity = mesDb.RankSets.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(10801);// "待编辑的记录不存在或已被删除，无法编辑");
                }

                mesDb.RankSets.Attach(entity);
                entity.ELRank = model.ELRank;
                entity.OutRank = model.OutRank;
                entity.FinalRank = model.FinalRank;
                entity.RankCode = model.RankCode;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
                mesDb.SaveChanges();

                model = Mapper.Map<VRankSet>(entity);
            }
            return model;
        }

        /// <summary>
        /// 查询
        /// </summary>
        public VRankSet GetRank(int pkId)
        {
            var entity = mesDb.RankSets.AsNoTracking().FirstOrDefault(_ => _.PkId == pkId && _.Valid);
            if (entity == null)
            {
                entity = new RankSet();
            }
            return Mapper.Map<VRankSet>(entity);
        }

        /// <summary>
        /// 搜索
        /// </summary>
        public List<VRankSet> QueryRank(int pageIndex, int pageSize, out int total, string elRank, string outRank, string finalRank)
        {
            var query = mesDb.RankSets.AsNoTracking().Where(_ => _.Valid);
            if (!string.IsNullOrWhiteSpace(elRank))
            {
                query = query.Where(_ => _.ELRank.Equals(elRank));
            }
            if (!string.IsNullOrWhiteSpace(outRank))
            {
                query = query.Where(_ => _.OutRank.Equals(outRank));
            }
            if (!string.IsNullOrWhiteSpace(finalRank))
            {
                query = query.Where(_ => _.FinalRank.Equals(finalRank));
            }

            total = query.Count();
            var entities = query.OrderByDescending(_ => _.PkId).Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(_ => _.PkId).ToList();

            return Mapper.Map<List<VRankSet>>(entities);
        }

        /// <summary>
        /// 删除
        /// </summary>
        public void DeleteRank(VRankSet model)
        {
            var entity = mesDb.RankSets.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity == null)
            {
                throw new MultiLanBizException(10802);// "数据不存在或已被删除，无法重复删除");
            }

            mesDb.RankSets.Attach(entity);
            entity.Valid = false;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询等级列表
        /// </summary>
        /// <returns></returns>
        public List<VQLevel> QueryLevels()
        {
            var entities = mesDb.QLevels.AsNoTracking().Where(_ => _.Valid).OrderBy(_ => _.SortNo).ToList();
            return Mapper.Map<List<VQLevel>>(entities);
        }

        #endregion

        #region 颜色
        /// <summary>
        /// 编辑
        /// </summary>
        public VColorSet EditColor(VColorSet model)
        {
            if (model.PkId <= 0)
            {
                model.CreateTime = DateTime.Now;
                model.ModifyBy = 0;
                var entity = Mapper.Map<ColorSet>(model);
                mesDb.ColorSets.Add(entity);
                mesDb.SaveChanges();

                model = Mapper.Map<VColorSet>(entity);
            }
            else
            {
                var entity = mesDb.ColorSets.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(10801);// "待编辑的记录不存在或已被删除，无法编辑");
                }

                mesDb.ColorSets.Attach(entity);
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
                mesDb.SaveChanges();

                model = Mapper.Map<VColorSet>(entity);
            }
            return model;
        }

        /// <summary>
        /// 查询
        /// </summary>
        public VColorSet GetColor(int pkId)
        {
            var entity = mesDb.ColorSets.AsNoTracking().FirstOrDefault(_ => _.PkId == pkId && _.Valid);
            if (entity == null)
            {
                entity = new ColorSet();
            }
            return Mapper.Map<VColorSet>(entity);
        }

        /// <summary>
        /// 搜索
        /// </summary>
        public List<VColorSet> QueryColor(int pageIndex, int pageSize, out int total, string compColor, string compColorCode)
        {
            var query = mesDb.ColorSets.AsNoTracking().Where(_ => _.Valid);
            total = query.Count();
            var entities = query.OrderByDescending(_ => _.PkId).Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(_ => _.PkId).ToList();

            return Mapper.Map<List<VColorSet>>(entities);
        }


        /// <summary>
        /// 删除
        /// </summary>
        public void DeleteColor(VColorSet model)
        {
            var entity = mesDb.ColorSets.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity == null)
            {
                throw new MultiLanBizException(10802);// "数据不存在或已被删除，无法重复删除");
            }
            mesDb.ColorSets.Attach(entity);
            entity.Valid = false;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }
        #endregion

        #region 重写

        #region 等级

        /// <summary>
        /// 查询等级分页
        /// </summary>
        public Tuple<List<VQLevel>, int> QueryLevels(int pageIndex, int pageSize)
        {
            var queryStr = mesDb.QLevels.AsNoTracking().Where(_ => _.Valid);
            var entities = queryStr.OrderBy(_ => _.SortNo).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();

            return new Tuple<List<VQLevel>, int>(Mapper.Map<List<VQLevel>>(entities), queryStr.Count());
        }

        /// <summary>
        /// 编辑等级
        /// </summary>
        public void EditLevel(QLevel model)
        {
            var entity = mesDb.QLevels.AsNoTracking().FirstOrDefault(_ => _.Valid && _.PkId == model.PkId);
            if (entity == null)
            {
                throw new MultiLanBizException(10801); // "待编辑的记录不存在或已被删除，无法编辑");
            }
            if (mesDb.QLevels.Any(_ => _.Level == model.Level && _.Valid && _.PkId != model.PkId))
            {
                throw new MultiLanBizException(134003);  // 等级名称已存在，无法编辑
            }

            mesDb.QLevels.Attach(entity);
            entity.Level = model.Level;
            entity.ErpLevel = model.ErpLevel;
            entity.SortNo = model.SortNo;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 新增等级
        /// </summary>
        public void AddLevel(QLevel model)
        {
            var entity = mesDb.QLevels.AsNoTracking().FirstOrDefault(_ => _.Level == model.Level && _.Valid);
            if (entity != null)
            {
                throw new MultiLanBizException(134003);  // 等级名称已存在，无法编辑
            }

            mesDb.QLevels.Add(model);
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 删除等级
        /// </summary>
        public void DeleteLevel(int pkId, int memberId)
        {
            var entity = mesDb.QLevels.AsNoTracking().FirstOrDefault(_ => _.PkId == pkId && _.Valid);
            if (entity == null)
            {
                throw new MultiLanBizException(10802); // 数据不存在或已被删除，无法重复删除
            }

            mesDb.QLevels.Attach(entity);
            entity.Valid = false;
            entity.ModifyBy = memberId;
            entity.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }

        #endregion

        #region 颜色

        /// <summary>
        /// 查询颜色配置分页
        /// </summary>
        public Tuple<List<VColorSet>, int> QueryColors(int pageIndex, int pageSize, ColorType? colorType)
        {
            var query = mesDb.ColorSets.AsNoTracking().Where(_ => _.Valid);
            if (colorType.HasValue)
            {
                query = query.Where(_ => _.ColorType == colorType.Value);
            }
            var count = query.Count();
            query = query.OrderByDescending(_ => _.PkId);
            var entities = pageSize <= 0 ? query.ToList() : query.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();

            return new Tuple<List<VColorSet>, int>(Mapper.Map<List<VColorSet>>(entities), count);
        }

        /// <summary>
        /// 编辑颜色
        /// </summary>
        public void EditColor(ColorSet model)
        {
            var entity = mesDb.ColorSets.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity == null)
            {
                throw new MultiLanBizException(10801); // "待编辑的记录不存在或已被删除，无法编辑");
            }
            if (mesDb.ColorSets.Any(_ => _.Valid && _.PkId != model.PkId && (model.Color == _.Color || model.ColorCode == _.ColorCode) && _.ColorType == model.ColorType))
            {
                throw new MultiLanBizException(134004);  // 当前分类，颜色代码或颜色名称已存在
            }

            mesDb.ColorSets.Attach(entity);
            entity.Color = model.Color;
            entity.ColorCode = model.ColorCode;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;

            mesDb.SaveChanges();
        }

        /// <summary>
        /// 新增颜色
        /// </summary>
        public void AddColor(ColorSet model)
        {
            var entity = mesDb.ColorSets.AsNoTracking().FirstOrDefault(_ => _.Valid && _.ColorType == model.ColorType && (_.Color == model.Color || _.ColorCode == model.ColorCode));
            if (entity != null)
            {
                throw new MultiLanBizException(134004); // 当前分类，颜色代码或颜色名称已存在
            }

            mesDb.ColorSets.Add(model);
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 删除颜色
        /// </summary>
        public void DeleteColor(int pkId, int memberId)
        {
            var entity = mesDb.ColorSets.AsNoTracking().FirstOrDefault(_ => _.PkId == pkId && _.Valid);
            if (entity == null)
            {
                throw new MultiLanBizException(10801); // "待编辑的记录不存在或已被删除，无法编辑");
            }

            mesDb.ColorSets.Attach(entity);
            entity.Valid = false;
            entity.ModifyBy = memberId;
            entity.ModifyTime = DateTime.Now;

            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询颜色匹配
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="workOrderNo">工单号</param>
        /// <returns>颜色列表</returns>
        public List<VColorMatch> QueryColorMatches(string orderNo, string workOrderNo)
        {
            var entities = new List<ColorMatch>();
            if (!string.IsNullOrWhiteSpace(workOrderNo))
            {
                entities.AddRange(mesDb.ColorMatches.AsNoTracking().Where(_ => _.OrderNo == "" && _.WorkOrderNo == workOrderNo && _.Valid).ToList());
                if (!entities.Any())
                {
                    var workOrder = mesDb.WorkOrders.AsNoTracking().FirstOrDefault(_ => _.WorkOrderNo == workOrderNo && _.Valid);
                    if (workOrder == null)
                    {
                        throw new MultiLanBizException(102022);//工单不存在
                    }
                    entities.AddRange(mesDb.ColorMatches.AsNoTracking().Where(_ => _.OrderNo == workOrder.OrderNo && _.WorkOrderNo == "" && _.Valid).ToList());
                }
            }
            else if (!string.IsNullOrWhiteSpace(orderNo))
            {
                entities.AddRange(mesDb.ColorMatches.AsNoTracking().Where(_ => _.OrderNo == orderNo && _.WorkOrderNo == "" && _.Valid).ToList());
            }

            return Mapper.Map<List<VColorMatch>>(entities);
        }

        /// <summary>
        /// 添加颜色匹配
        /// </summary>
        /// <param name="model">颜色匹配</param>
        public void AddColorMatch(VColorMatch model)
        {
            var colors = mesDb.ColorSets.AsNoTracking().Where(_ => _.Valid).ToList();
            var cellColor = colors.FirstOrDefault(_ => StringUtils.Equals(model.CellColorCode, _.ColorCode));
            var componentColor = colors.FirstOrDefault(_ => StringUtils.Equals(model.ComponentColorCode, _.ColorCode));
            if (cellColor == null)
            {
                throw new MultiLanBizException(10803);//电池片颜色不存在
            }
            else if (componentColor == null)
            {
                throw new MultiLanBizException(10804);//组件颜色不存在
            }
            model.CellColor = cellColor.Color;
            model.ComponentColor = componentColor.Color;
            model.CreateTime = DateTime.Now;
            var entity = Mapper.Map<ColorMatch>(model);

            if (string.IsNullOrWhiteSpace(model.WorkOrderNo))
            {
                var exist = mesDb.ColorMatches.AsNoTracking().Count(_ => _.OrderNo == model.OrderNo && _.WorkOrderNo == "" && _.CellColorCode == model.CellColorCode && _.ComponentColorCode == model.ComponentColorCode && _.Valid);
                if (exist > 0)
                {
                    return;
                }
                mesDb.ColorMatches.Add(entity);
            }
            else
            {
                var exists = mesDb.ColorMatches.AsNoTracking().Where(_ => _.OrderNo == "" && _.WorkOrderNo == model.WorkOrderNo && _.Valid).ToList();
                if (!exists.Any())
                {
                    var workOrder = mesDb.WorkOrders.AsNoTracking().FirstOrDefault(_ => _.WorkOrderNo == model.WorkOrderNo && _.Valid);
                    if (workOrder == null)
                    {
                        throw new MultiLanBizException(102022);//工单不存在
                    }
                    exists = mesDb.ColorMatches.AsNoTracking().Where(_ => _.OrderNo == workOrder.OrderNo && _.WorkOrderNo == "" && _.Valid).ToList();
                    if (exists.Any(_ => StringUtils.Equals(_.CellColorCode, model.CellColorCode) && StringUtils.Equals(_.ComponentColorCode, model.ComponentColorCode)))
                    {
                        return;
                    }
                    exists.ForEach(_ =>
                    {
                        _.PkId = 0;
                        _.OrderNo = string.Empty;
                        _.WorkOrderNo = model.WorkOrderNo;
                        _.CreateBy = model.CreateBy;
                        _.CreateTime = DateTime.Now;
                        _.ModifyBy = 0;
                        _.ModifyTime = null;
                    });
                    mesDb.ColorMatches.AddRange(exists);
                }
                entity.OrderNo = string.Empty;
                mesDb.ColorMatches.Add(entity);
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 移除颜色匹配
        /// </summary>
        /// <param name="model">颜色匹配对象</param>
        public void RemoveColorMatch(VColorMatch model)
        {
            var entity = mesDb.ColorMatches.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity == null)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(model.WorkOrderNo)) //订单下删除
            {
                mesDb.ColorMatches.Attach(entity);
                entity.Valid = false;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
            }
            else //工单下删除
            {
                if (!string.IsNullOrWhiteSpace(entity.WorkOrderNo))//工单下删除工单配置
                {
                    mesDb.ColorMatches.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.ModifyBy;
                    entity.ModifyTime = DateTime.Now;
                }
                else //工单下删除订单配置
                {
                    var exists = mesDb.ColorMatches.AsNoTracking().Where(_ => _.PkId != model.PkId && _.OrderNo == entity.OrderNo && _.WorkOrderNo == "" && _.Valid).ToList();
                    if (exists.Any())
                    {
                        exists.ForEach(_ =>
                        {
                            _.PkId = 0;
                            _.OrderNo = string.Empty;
                            _.WorkOrderNo = model.WorkOrderNo;
                            _.CreateBy = model.ModifyBy;
                            _.CreateTime = DateTime.Now;
                            _.ModifyBy = 0;
                            _.ModifyTime = null;
                        });
                        mesDb.ColorMatches.AddRange(exists);
                    }
                }
            }
            mesDb.SaveChanges();
        }
        #endregion
        #endregion
    }
}
